extends Node2D

@export var power = 10 			## 伤害
@export var length = 10			## 抖动总时长
@export var time_add = 0.5		## 抖动帧率, 越小帧率越高
@export var shake_range = 20	## 抖动角度, 越大角度越大
@export var freq = 0.02			## 抖动频率, 越小频率越高

@onready var camera = null
@onready var remote = null
@onready var boomAudio = $Boom
@onready var boomAfterAudio = $BoomAfter
@onready var boomAnimation = $AnimatedSprite2D
@onready var util = Util.new()
@onready var powerScope = $BoomHitBox/CollisionShape2D

var step = 0		# 阶段
var time = 0		# 炸弹抖动计时

func _ready():
	# 获得摄像机
	camera = util.findOne("#[Camera2D]", self)
	# 获得摄像机跟随对象
	var ysort = util.findOne("#[YSort]", self)
	var player = util.findOne("$[Player]", ysort)
	remote = util.findOne("$[RemoteTransform2D]", player)
	
	# 禁用炸点碰撞体
	powerScope.disabled = true
	boomAudio.play()
	boomAnimation.play("boom")
	# 动画播放完毕后执行boomAnimationFinished函数
	boomAnimation.connect("animation_finished", boomAnimationFinished)

func boomAnimationFinished():
	step += 1
	match step:
		1: # 第一次播放完毕, 预爆炸动画
			# 开启炸弹碰撞体, 造成伤害
			powerScope.disabled = false
			shake_camera()
			
			# 停止播放第一阶段音频
			boomAudio.stop()
			# 播放第二阶段音频
			boomAfterAudio.play()
		2: # 第二次播放完毕, 爆炸动画
			# 动画完成后, 重新将摄像机交给系统
			boomAfterAudio.stop()
			queue_free()
			
	boomAnimation.play("boomAfter")


'''
	镜头摇晃
'''
func shake_camera():
	var camera_position = camera.position
	while time < length:
		time += time_add
		# 随机摇晃
		var new_position = camera_position
		
		# 随机摇晃
		new_position += Vector2(randf_range(-shake_range, shake_range),
								randf_range(-shake_range, shake_range))
		
		camera.position = new_position
		# 使用 await 代替 yield
		await get_tree().create_timer(freq).timeout
		
	# 恢复原始位置
	camera.position = camera_position
